// 2013-7-29下午02:48:59  net.betou.trade.admin.action.CategoryAct.java

package net.betou.trade.admin.action;

import static net.betou.common.page.SimplePage.cpn;
import static net.betou.common.page.SimplePage.cpnPageSize;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.betou.common.page.Pagination;
import net.betou.common.util.TradeUtils;
import net.betou.core.service.post.SmsPost;
import net.betou.core.service.post.Task;
import net.betou.trade.action.abs.ActionSupport;
import net.betou.trade.entity.main.AgentAndAdmins;
import net.betou.trade.entity.main.Notice;
import net.betou.trade.main.manager.NoticeMng;
import net.betou.trade.main.manager.NoticeTypeMng;
import net.betou.trade.main.manager.UserGroupMng;
import net.betou.trade.main.manager.role.AgencyRoleMng;
import net.betou.trade.web.Messages;
import net.betou.trade.web.ResponseUtil;
import net.betou.trade.web.WebErrors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 公告
 * @author 叶装装
 */
@Controller
public class NoticeAct extends ActionSupport< Notice >{
	
	private static final String DIRECTORY = "notice";
	private static final Logger log = LoggerFactory.getLogger( NoticeAct.class );
	
	@RequestMapping( "/notice/v_list.jspx" )
	public String list(  Integer pageSize, Integer pageNo, String searchProperty, String searchValue, String orderProperty, String orderDirection, String filterStatus, HttpServletRequest request, HttpServletResponse response, ModelMap model  ){
		
		pageSize = cpnPageSize( pageSize );
		pageNo = cpn( pageNo );
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request ); // 获取当前管理员
		Pagination pagination = manager.getPage( admin, searchProperty, searchValue, orderProperty, orderDirection, filterStatus, pageNo, pageSize );
		
		// 设置类别列表
		if( admin.getSystem( ) ){
			model.addAttribute( "typeList", mng.getList( null, null, null, null ) );
		}
		
		model.addAttribute( "admin", admin );
		paramToModel( model, pagination, null, pageSize, searchProperty, searchValue, orderProperty, orderDirection, filterStatus );
		
		return getListPage( );
	}
	
	@RequestMapping( "/notice/v_add.jspx" )
	public String v_add( HttpServletRequest request, ModelMap model ){
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request ); // 获取当前管理员
		
		if( !admin.getSystem( ) ){
			// 是机构的话，就查找出代理商选项
			if( admin.getAgency( ) ){
				model.addAttribute( "group",  roleMng.findProxyBySelf( admin ) );
			}
			
			model.addAttribute( "groupList", groupMng.getAllowReadList( null, null, null, null ) );
		}
		model.addAttribute( "admin", admin );
		return getAddPage( );
	}
	
	@RequestMapping( "/notice/o_save.jspx" )
	public String o_save( Notice bean,  HttpServletRequest request, Integer [ ] mxGroups, Integer [ ] smsGroups, HttpServletResponse response, ModelMap model ){
		
		WebErrors errors = validateSave( bean );
		
		if( errors.hasErrors( ) ){
			return errors.showErrorPage( model );
		}
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request ); // 获取当前管理员
		
		bean = manager.save( bean, admin, mxGroups, smsGroups );
		
		logMng.operating( 0, request, Messages.LOG_NOTICE, "id=" + bean.getId( ) + ",title=" + bean.getTitle( )  );
		
		// 监听器中没有HttpServletRequest, HttpServletResponse 对象，所以只能在这里实现
		// 保存完毕增加cookie
		
		
		return "redirect:v_list.jspx";
	}
	
	@RequestMapping ( "/notice/v_edit.jspx" )
	public String v_edit( Integer id, HttpServletRequest request, ModelMap model ){

		WebErrors errors = validateUpdate( request, id );
		
		if( errors.hasErrors( ) ){
			return errors.showErrorPage( model );
		}
		
		Notice bean = manager.findById( id );
		
		model.addAttribute( "bean", bean );
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request ); // 获取当前管理员
		
		if( !bean.getNoticeType( ).getIdentity( ).equals( "s" ) ){
			// 是机构的话，就查找出代理商选项
			if( admin.getAgency( ) ){
				model.addAttribute( "group",  roleMng.findProxyBySelf( admin ) );
			}
			
			model.addAttribute( "groupList", groupMng.getAllowReadList( null, null, null, null ) );
		}
		model.addAttribute( "admin", admin );
		
		
		return getUpdatePage( );
	}
	
	@RequestMapping ( "/notice/o_update.jspx" )
	public String o_update(  Integer id, Integer [ ] mxGroups, Integer [ ] smsGroups, Notice bean, HttpServletRequest request, ModelMap model ){
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request ); // 获取当前管理员
		
		WebErrors errors = validateOUpdate( request, id, admin.getId( ), admin.getSystem( ) );
		
		if( errors.hasErrors( ) ){
			return errors.showErrorPage( model );
		}
		
		bean = manager.update( bean, mxGroups, smsGroups );
		
		logMng.operating( 1, request, Messages.LOG_NOTICE, "id=" + bean.getId( ) + ",title=" + bean.getTitle( ) );
		
		return "redirect:v_list.jspx";
	}
	
	
	@RequestMapping( "/notice/o_delete.jspx" )
	public void o_delete( Integer [ ] ids, HttpServletResponse response, HttpServletRequest request ){
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request ); // 获取当前管理员
		
		ResponseUtil util = validateDelete( ids, admin.getId( ), admin.getSystem( ), response, request );

		if( util.hasResponse( ) ){
			util.renderJson( );
			return;
		}

		Notice [ ] beans = manager.deleteByIds( ids );

		for ( Notice bean : beans ){
			log.info( "delete Notice id={}", bean.getId( ) );
			logMng.operating( 2, request, Messages.LOG_NOTICE, "id=" + bean.getId( ) + ",title=" + bean.getTitle( ) );
		}

		util.addSuccessResponse( Messages.getDeleteSuccessMessage( beans.length ) );

		util.renderJson( );
		return;
		
	}
	@RequestMapping( "/notice/o_send.jspx" )
	public void o_send( Integer id, HttpServletResponse response, HttpServletRequest request ){
		
		AgentAndAdmins admin = TradeUtils.getAdmin( request ); // 获取当前管理员
		ResponseUtil util = ResponseUtil.create( response );
		
		Notice bean = manager.findMyNotice( id, admin.getId( ), admin.getSystem( ) );
		
		if( bean == null ){
			util.addErrorResponse(  admin.getSystem( ) ? Messages.DATA_NOT_EXIST : Messages.DATA_NOT_OPERATING   );
			util.renderJson( );
			return;
		}
		
		util = validateSmsSend( bean.getSmsSendGroup( ) , bean.getSmsContent( ), response );
		
		if( util.hasResponse( ) ){
			util.renderJson( );
			return;
		}
		
		post.setAdmin( bean.getAdmin( ) );
		post.setSmsGroups( bean.getSmsSendGroup( ) );
		post.setContent( clearHtml( bean.getSmsContent( ) ) );
		
		task.addTask( post );
		
		util.addSuccessResponse( Messages.DATA_SMS_SEND_SUCCESS );
		util.renderJson( );
		return;
	}
	
	private ResponseUtil validateDelete( Integer [ ] ids, Integer selfId, Boolean system, HttpServletResponse response, HttpServletRequest request ) {
		ResponseUtil util = ResponseUtil.create( response );

		if( ids == null || ids.length == 0 ){
			util.addErrorResponse( Messages.DATA_NOT_SELECT );
			return util;
		}

		for ( Integer id : ids ){
			Notice bean = manager.findMyNotice( id, selfId, system );
			
			if( bean == null ){
				util.addErrorResponse(  system ? Messages.DATA_NOT_EXIST : Messages.DATA_NOT_OPERATING   );
				break;
			}
		}
		return util;
	}
	
	
	private WebErrors validateOUpdate( HttpServletRequest request, Integer id, Integer selfId, Boolean system ){
		WebErrors errors = WebErrors.create( );
		
		if( id == null || id == 0 ){
			errors.addError( Messages.DATA_NOT_EXIST );
			return errors;
		}
		
		Notice bean = manager.findMyNotice( id, selfId, system );
		
		if( bean == null ){
			errors.addError( system ? Messages.DATA_NOT_EXIST : Messages.DATA_NOT_OPERATING );
			return errors;
		}
		
		return errors;
			
	}
	
	private WebErrors validateUpdate( HttpServletRequest request, Integer id ){
		WebErrors errors = WebErrors.create( );
		
		if( id == null || id == 0 ){
			errors.addError( Messages.DATA_NOT_EXIST );
			return errors;
		}
		
		Notice bean = manager.findById( id );
		
		if( bean == null ){
			errors.addError( Messages.DATA_NOT_EXIST );
			return errors;
		}
		
		return errors;
			
	}
	
	private WebErrors validateSave( Notice bean ){
		WebErrors errors = WebErrors.create( );
		return errors;
	}
	
	@Override
	protected String getDirectory( ) {
		return DIRECTORY;
	}
	
	@Autowired
	private AgencyRoleMng roleMng;
	
	@Autowired
	private UserGroupMng groupMng;
	
	@Autowired
	private NoticeMng manager;
	
	@Autowired
	private NoticeTypeMng mng;
	
	@Autowired
	private SmsPost post;
	
	@Autowired
	protected Task task;

}
